const CanvasWidth = 420 // canvas宽高
const CanvasHeight = 420
const QueueSize = 7 // 缓冲队列大小
const MapBlockSize = 60 // 地图块大小

const canvas = document.getElementById('canvas')
const queueBox = document.querySelector('.queue')
const ctx = canvas.getContext('2d')
const mapArr = [] // 管理所有地图层
const Images = []
let queue // 队列

    // init
;(async () => {
    canvas.height = CanvasHeight
    canvas.width = CanvasWidth
    const loadResult = await Utils.asyncLoadImage()
    Images.push(...loadResult)
    initMap()
    // fill background
    const box = document.getElementsByClassName('queue')[0]
    for (let i = 0; i < QueueSize; i++) {
        const div = document.createElement('div')
        div.className = 'queue-box-item'
        box.appendChild(div)
    }
    queue = new Queue(QueueSize)
})()

function initMap() {
    const map1 = new GameMap('map1', CanvasWidth, CanvasHeight, 0, 6, 1, MapBlockSize)
    const map2 = new GameMap('map2', CanvasWidth, CanvasHeight, 1, 5, 1, MapBlockSize)
    const map3 = new GameMap('map3', CanvasWidth, CanvasHeight, 2, 4, 1, MapBlockSize)
    mapArr.push(map1)
    mapArr.push(map2)
    mapArr.push(map3)
    mapArr.forEach(map => map.draw())
}

function drawBg() {
    ctx.fillStyle = '#eee'
    ctx.fillRect(0, 0, CanvasWidth, CanvasHeight)
}

canvas.addEventListener('click', e => {
    // 这里的顺序是反的
    const X = e.offsetY
    const Y = e.offsetX
    let hit // 命中信息
    for (let i = mapArr.length - 1; i >= 0; i--) {
        if ((hit = mapArr[i].isInMap(X, Y))) {
            break
        }
    }
    if (!hit) return
    let permitClick = true
    const { index } = hit
    console.log(hit)
    for (let i = index; i < 3; i++) {
        const hasOverBlock = mapArr[i].hasOverBlock(hit)
        if (hasOverBlock) {
            permitClick = false
            break
        }
    }
    if (!permitClick) {
        console.log('不可以点击')
        return
    }

    // 这里应该遍历判断哪层地图是最顶层
    const value = hit.payload
    if (!value.type) return
    // 更新地图数据，并重新绘制地图
    ctx.clearRect(0, 0, CanvasWidth, CanvasHeight)
    hit.map.update(
        { indexX: hit.origincoordinate.indexX, indexY: hit.origincoordinate.indexY },
        null
    )
    mapArr.forEach(map => map.draw())
    // 更新队列并在isFull方法中处理数据和操作DOM
    queue.push({
        originX: hit.origincoordinate.indexX,
        originY: hit.origincoordinate.indexY,
        source: { type: value.type }
    })
    if (queue.isFull()) {
        alert('GameOver')
        // map.reset()
    }
    if (queue.isEmpty) {
        for (let map of mapArr) {
            const res = map.isEmptyMap()
            if (!res) return
        }
        alert('游戏通关')
    }
})
